package com.bangcommunity.bbframe.monitor.logger;

import com.bangcommunity.bbframe.common.utils.lang.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author tanghc
 * @date 18/1/29
 */
public abstract class LogFileAccessor {

    private static final String LOG_PATH = "/opt/logs/";
    private static final String LOG_PATH_PARAM = "mlogPath";

    /**
     * 返回文件路径。 1、判断路径是否有文件,有 则返回,无则判断是否能创建文件,能则返回。此处路径优先"/opt/logs/",然后系统参数mlogPath
     * 2、如果上面两个路径都不行则使用相对路径./filename
     */
    public static String getFilePath(String fileName) {
        String filePathName = LOG_PATH + fileName;
        if (existOrCanCreate(filePathName)) {
            return filePathName;
        }
        String property = System.getProperty(LOG_PATH_PARAM);
        if (StringUtils.isNotBlank(property)) {
            if (!property.endsWith(File.pathSeparator)) {
                property = property + File.pathSeparator;
            }
            filePathName = property + fileName;
            if (existOrCanCreate(filePathName)) {
                return filePathName;
            }
        }
        return "." + File.pathSeparator + fileName;
    }

    private static boolean existOrCanCreate(String filePathName) {
        File file = new File(filePathName);
        if (file.exists()) {
            return true;
        }
        try {
            if (file.createNewFile()) {
                return true;
            }
        } catch (IOException e) {
        }
        return false;
    }

}